//我的收货地址
$("#add-postcode").keyup(function () {
    var val = t = $(this).val();
    var reg = new RegExp("^[0-9]*$");
    if (!reg.test(t)) {
        val = ''
    }
    if (t != '') {
        //  var val = isNaN(t*1)?0:$(this).val()*1;
        // val = val.toString();
        if (val.length > 6) {
            val = val.substr(0, 6);
        }
        $(this).val(val)
    }
})

$("#add-mobil").keyup(function () {
    var val = t = $(this).val();
    var reg = new RegExp("^[0-9]*$");
    if (!reg.test(t)) {
        val = ''
    }
    if (t != '') {
        // var val = isNaN(t * 1) ? 0 : $(this).val() * 1;
        //  val = val.toString();
        if (val.length > 11) {
            val = val.substr(0, 11);
        }
        $(this).val(val)
    }
})
$("#tel-code").keyup(function () {
    var val = t = $(this).val();
    var reg = new RegExp("^[0-9]*$");
    if (!reg.test(t)) {
        val = ''
    }
    if (t != '') {
        //  var val = isNaN(t * 1) ? 0 : t * 1;
        //  val = val.toString();
        if (val.length > 5) {
            val = val.substr(0, 5);
        }
        $(this).val(val)
    }
})
$("#tel-num").keyup(function () {
    var val = t = $(this).val();
    var reg = new RegExp("^[0-9]*$");
    if (!reg.test(t)) {
        val = ''
    }
    if (t != '') {
        // var val = isNaN(t * 1) ? 0 : t * 1;
        // val = val.toString();
        if (val.length > 8) {
            val = val.substr(0, 8);
        }
        $(this).val(val)
    }
})
$("#tel-cell").keyup(function () {
    var val = t = $(this).val();
    var reg = new RegExp("^[0-9]*$");
    if (!reg.test(t)) {
        val = ''
    }
    if (t != '') {

        if (val.length > 8) {
            val = val.substr(0, 8);
        }
        $(this).val(val)
    }
})

$(function () {
    var ifrm = $("#couponlist");
    $('#item-list-tabs li a').click(function () {
        var src = $(this).attr("href");
        ifrm.attr("src", src);
        $(this).parent("li").addClass("selected").siblings().removeClass("selected");
        return false;

    });
    //地址选择控件


//添加地址验证
    function validateAddress() {
        var defaultAdd = false;
        var btn = $('.short-btn');
        var name_ipt = $('[name=contact]');
        var box = $("#add-street");
        var postcode_ipt = $("#add-postcode");
        var tel_code_ipt = $('.input-tel-code');
        var tel_num_ipt = $('.input-tel-num');
        var tel_cell_ipt = $('#tel-cell');
        var mobile_ipt = $("#add-mobil");
        btn.click(function (check) {
            var errorFlag = true;
            var name = $.trim(name_ipt.val());
            var province = $("#province option:selected").html();
            var city = $("#city option:selected").html();
            var country = $("#country option:selected").html();
            var region_id = $("#country").val();
            var address = $.trim(box.val());
            var postcode = postcode_ipt.val();
            var tel_code = tel_code_ipt.val();
            var tel_num = tel_num_ipt.val();
            var tel_cell = tel_cell_ipt.val();
            var mobil = mobile_ipt.val();
            var id = $('#addr_id').val();
            //石峰 改 2016-8-3


//            if ($('#statusAddr').attr("checked") == true || $('#statusAddr').is(':checked') ) {
//                defaultAdd = true;
//            }

            if (name == '') {
                error("此项必填", name_ipt.parents("li"));
                errorFlag = false;
            } else {
                name_ipt.parents("li").find(".msg").remove();
            }
            if (region_id == 0) {
                error("请选择所在的地区", $("#country").parents("li"));
                errorFlag = false;
            } else {
                $("#country").parents("li").find(".msg").remove();

            }
            if (address == '') {
                error("此项必填", $("#add-street").parents("li"));
                errorFlag = false;
            } else if (address.length < 4 || address.length > 60) {
                error("区县以下的街道地址最少要4个字，最多不能超过60个字", $("#add-street").parents("li"));
                errorFlag = false;
            } else if (/^[0-9]+$/.test(address)) {
                error("区县以下的街道地址不能全是数字，请重新填写", $("#add-street").parents("li"));
                errorFlag = false;
            } else if (/^[a-z]+$/.test(address) || /^[A-Z]+$/.test(address)) {
                error("区县以下的街道地址不能全是英文字母，请重新填写", $("#add-street").parents("li"));
                errorFlag = false;
            } else {
                $("#add-street").parents("li").find(".msg").remove();
            }

           /*  if (postcode == '') {
                error("邮政编码填写有误，请输入6位邮政编码", $("#add-postcode").parents("li"));
                errorFlag = false;
            } else */ 
		 if(postcode!=''){
			if (!(/^\d{6}$/g.test(postcode))) {
                error("邮政编码填写有误，请输入6位邮政编码", $("#add-postcode").parents("li"));
                errorFlag = false;
            } else {
                $("#add-postcode").parents("li").find(".msg").remove();
            } 
		 }
			

            if (mobil == '') {
                error("此项必填", $("#add-mobil").parents("li"));
                errorFlag = false;
            } else if (!(/^1\d{10}$/g.test(mobil)) && !(/^\d?861\d{10}$/g.test(mobil))) {
                error("手机号码格式不对", $("#add-mobil").parents("li"));
                errorFlag = false;
            } 
            else {
                $("#add-mobil").parents("li").find(".msg").remove();
            }
            /*if (tel_code == '' && tel_num == '' && mobil == '') {
                error("电话和手机不能都为空", $("#add-mobil").parents("li"));
                $(".input-tel-code").parents("li").find(".msg").remove();
                errorFlag = false;
            }*/
            if (tel_code != "") {
                if (!(/^0[1-9][0-9]{1,3}$/g.test(tel_code))) {
                    error("区号必须由3到5位数字构成", $(".input-tel-code").parents("li"));
                    //$("#add-mobil").parents("li").find(".msg").remove();
                    errorFlag = false;
                } else {
                    if (tel_num == "") {
                        error("请填写正确的电话", $(".input-tel-code").parents("li"));
                        //$("#add-mobil").parents("li").find(".msg").remove();
                        errorFlag = false;
                    } else {
                        if (!(/^[1-9]\d{6,7}$/g.test(tel_num))) {
                            $(".input-tel-code").parents("li").find(".msg").remove();
                            error("请填写正确的电话", $(".input-tel-code").parents("li"));
                            errorFlag = false;
                        } else {
                            if (tel_cell != '') {
                                if (!(/^[0-9]{0,11}$/g.test(tel_cell))) {
                                    $(".input-tel-code").parents("li").find(".msg").remove();
                                    error("请填写正确的电话", $(".input-tel-code").parents("li"));
                                    errorFlag = false;
                                } else {
                                    $(".input-tel-code").parents("li").find(".msg").remove();
                                }
                            } else {
                                $(".input-tel-code").parents("li").find(".msg").remove();
                            }
                        }
                    }
                }
            }
            /*if (tel_code == "" && tel_num == "") {
                if (mobil != "") {
                    if (!(/^1\d{10}$/g.test(mobil)) && !(/^\d?861\d{10}$/g.test(mobil))) {
                        error("手机号码格式不对", $("#add-mobil").parents("li"));
                        $(".input-tel-code").parents("li").find(".msg").remove();
                        errorFlag = false;
                    } else {
                        $("#add-mobil").parents("li").find(".msg").remove();
                    }
                }
            }*/
            /*if (tel_code != "" && tel_num != "") {
                if (mobil != '') {
                    if (!(/^1\d{10}$/g.test(mobil)) && !(/^\d?861\d{10}$/g.test(mobil))) {
                        error("手机号码格式不对", $("#add-mobil").parents("li"));
                        $(".input-tel-code").parents("li").find(".msg").remove();
                        errorFlag = false;
                    } else {
                        $("#add-mobil").parents("li").find(".msg").remove();
                    }
                } else {
                    $("#add-mobil").parents("li").find(".msg").remove();
                }
            }*/
            if (mobil != '') {
                if (tel_code != "") {
                    if (!(/^0[1-9][0-9]{1,3}$/g.test(tel_code))) {
                        error("区号必须由3到5位数字构成", $(".input-tel-code").parents("li"));
                        $("#add-mobil").parents("li").find(".msg").remove();
                        errorFlag = false;
                    } else {
                        if (tel_num == "") {
                            error("请填写正确的电话", $(".input-tel-code").parents("li"));
                            $("#add-mobil").parents("li").find(".msg").remove();
                            errorFlag = false;
                        } else {
                            if (!(/^[1-9]\d{6,7}$/g.test(tel_num))) {

                                $(".input-tel-code").parents("li").find(".msg").remove();
                                error("请填写正确的电话", $(".input-tel-code").parents("li"));
                                errorFlag = false;
                            } else {
                                if (tel_cell != '') {
                                    if (!(/^[0-9]{0,11}$/g.test(tel_cell))) {
                                        $(".input-tel-code").parents("li").find(".msg").remove();
                                        error("请填写正确的电话", $(".input-tel-code").parents("li"));
                                        errorFlag = false;
                                    } else {
                                        $(".input-tel-code").parents("li").find(".msg").remove();
                                    }
                                } else {
                                    $(".input-tel-code").parents("li").find(".msg").remove();
                                }
                            }
                        }
                    }
                } else {
                    $(".input-tel-code").parents("li").find(".msg").remove();
                }
            }
            if (tel_num != '') {
                if (!(/^[1-9]\d{6,7}$/g.test(tel_num))) {
                    $(".input-tel-code").parents("li").find(".msg").remove();
                    error("请填写正确的电话", $(".input-tel-code").parents("li"));
                    $("#add-mobil").parents("li").find(".msg").remove();
                    errorFlag = false;
                } else if (tel_code == "") {
                    if (!(/^0[1-9][0-9]{1,2}$/g.test(tel_code))) {
                        error("请填写由3到6位数字构成的区号", $(".input-tel-code").parents("li"));
                        $("#add-mobil").parents("li").find(".msg").remove();
                        errorFlag = false;
                    } else {
                        if (tel_cell != '') {
                            if (!(/^[0-9]{0,11}$/g.test(tel_cell))) {
                                $(".input-tel-code").parents("li").find(".msg").remove();
                                error("请填写正确的电话", $(".input-tel-code").parents("li"));
                                errorFlag = false;
                            } else {
                                $(".input-tel-code").parents("li").find(".msg").remove();
                            }
                        }
                    }
                }
            }
            if (!errorFlag) {
                check.preventDefault();
                return false;
            }
            if ($("tr.odd_row").length >= 20) {
                alert("亲，您添加的地址够多了，还加啊！");
                check.preventDefault();
                return false;
            }
            if (tel_code != "") {
                var telphone_number = tel_code + "-" + tel_num;

                if (tel_cell != "")
                    telphone_number += "-" + tel_cell;

                $("input[name='telphone_number']").val(telphone_number);
            }

            var region_name = "";

            if (city == "市辖区" || city == "县") {
                region_name = province + country;
            } else {
                region_name = province + city + country;
            }
            //$("input[name='region_name']").val(region_name);
            //$("input[name='region_id']").val(region_id);

            var send = {};


            var statusAddr_ = $('#statusAddr').is(':checked');
            console.log(statusAddr_);
            send.consignee = name;
            send.region_id = region_id;
            send.region_name = region_name;
            send.address = address;
            send.zipcode = postcode;
            send.phone_tel = telphone_number;
            send.phone_mob = mobil;
            send.statusAddr = statusAddr_ ? 1 : 0;

            $.post('http://www.wjyh.com/index.php?app=member/BAddress&act=save&id=' + id, send, function (data) {

                if (data.err == 1 || data.err == 3) {
                    alert(data.msg);
                    window.location.reload();
                } else {
                    alert(data.msg);
                }
            }, 'json');
        });
        // 验证样式
        function error(txt, target) {
            var error_msg = $('<span class="msg"><span class="error">' + txt + '</span></span>');
            if (target.find(".msg").length) {
                target.find(".msg").remove();
            }
            target.append(error_msg);
            return;
        }
    }
    validateAddress();

//默认地址
    var default_add_btn = '<a href="javascript:void(0);" class="default_add_btn" onclick="defaultAddress($(this))">设为默认</a>';

    $('.thead-tbl-address:not(".default_address")').hover(function () {

        $(this).css("background-color", '#E1EBF7');
        $(this).find('.thead-tbl-status').append(default_add_btn);
    }, function () {
        $(this).css("background-color", 'white');
        $(this).find('.thead-tbl-status').empty();
    })

});
var args = {
    "_defaultValue": {
        "province": "请选择省份...",
        "city": "请选择市...",
        "country": "请选择县/区..."
    },
    "_elements": {
        "province": $("#province"),
        "city": $("#city"),
        "country": $("#country")
    },
    "_pid": 1
};
var region = new Region(args);
$("#province").change(function () {
    region.changeEvent(this);
});
$("#city").change(function () {
    region.changeEvent(this);
});

//修改地址
function editAddress(obj) {
    var t = obj, tr = t.parents(".thead-tbl-address");
    var name = tr.find(".name").html(), province = tr.find(".province"), city = tr.find(".city"), country = tr.find(".country"), street = tr.find("td:eq(2)").html(), code = tr.find("td:eq(3)").html(),
            tel = tr.find("td:eq(4) .telephone").html(), mobile = tr.find("td:eq(4) .mobile").html();
    var province_id = parseInt(province.val());
    var city_id = parseInt(city.val());
    var country_id = parseInt(country.val());
    var isDefault = tr.find('.default_address').attr('gdata-value');
    var checkVObj =
            {
                'province': {'pid': 1, 'region_id': province_id},
                'city': {'pid': province_id, 'region_id': city_id},
                'country': {'pid': city_id, 'region_id': country_id}
            };
    $('#addressForm').find(".msg").remove();
    region.upSelect(checkVObj);//地址显示
    $('#contact').val(name);
    $('#add-street').val(street);
    $('#add-postcode').val(code);
    $('#add-mobil').val(mobile);
    var telArr = tel.split('-');
    $('#tel-code').val(telArr[0]);
    $('#tel-num').val(telArr[1]);
    $('#tel-cell').val(telArr[2]);
    $('#addr_id').val(obj.attr('id'));
    if (isDefault == 1) {
        $('#statusAddr').attr('checked', 1);
    } else {
        $('#statusAddr').attr('checked', 0);
    }

}
//删除地址
function delAddress(obj) {
    var addPopupContent = $(".popup_content").length;
    var attr_id = obj.attr("id");
    showLayer(500, 'popup_content_alert', '你确定要删除此条记录吗？', function () {
        $.get("http://www.wjyh.com/index.php?app=member/BAddress&act=drop&id=" + attr_id, function (data) {
            obj.parent().parent().remove();
            hidePop();
            if (data.err == 0)
            {
                window.alert(data.msg);
                return;
            }
            window.location.reload();
        }, 'json');
    })
}



//默认地址
function defaultAddress(obj) {
    var t = obj.parents(".thead-tbl-address");
    var new_id = $(t).attr('gdata-id');
    var old_id = $('.thead-tbl-address').filter('.default_address').attr('gdata-id');
    $.ajax({
        url: "http://www.wjyh.com/index.php?app=member/BAddress&act=changeStatus",
        type: "GET",
        dataType: 'json',
        data: {'new_id': new_id, 'old_id': old_id},
        success: function (data) {
            if (data === true) {
                alert('更新默认地址成功！');
                window.location.reload();
            } else if (data === false) {
                alert('更新默认地址失败!');
            }
        }
    })

}